﻿using Core.SimpleTemp.Application;
using Core.SimpleTemp.Application.ZY;
using Core.SimpleTemp.Application.ZY.Dto;
using Core.SimpleTemp.Common.AutoMapperExtend;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Api.Api
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/[controller]")]
    [EnableCors("any")]
    [ApiExplorerSettings(GroupName = "Sys")]
    [Authorize]
    [ApiController]
    public class JobSlipController : CoreApiController
    {

        private readonly CoreDBContext _coreDBContext;
        /// <summary>
        /// 
        /// </summary>
        public JobSlipController(CoreDBContext coreDBContext)
        {
            _coreDBContext = coreDBContext;
        }



        /// <summary>
        /// 获取作业信息
        /// 作业单位，属地主管
        /// </summary>
        [HttpGet("Jobinformation/{areaId}")]
        public async Task<ActionResult> Jobinformation(Guid areaId)
        {

            SysDepartment department = null;
            List<SysUserInfor> users = null;

            var area = _coreDBContext.SysArea.FirstOrDefault(a => a.Id == areaId);
            var dutyID = area.LeadDutyID;//负责岗位ID
            if (dutyID == null)
                return this.JsonFaild("未找到该区域设置岗位信息");
            var dutyModel = _coreDBContext.SysDuty.FirstOrDefault(a => a.Id == dutyID);
            if (dutyModel == null)
                return this.JsonFaild("根据区域设置的对岗位信息");
            department = _coreDBContext.SysDepartment.FirstOrDefault(a => a.Id == dutyModel.SysDepartmentID);
            if (department == null)
                return this.JsonFaild("岗位信息未设置部门关系");
            var userDepartmentDutys = await _coreDBContext.SysUserDepartmentDuty.Where(a => a.SysDepartmentID == department.Id).ToListAsync();
            if (userDepartmentDutys == null)
                return this.JsonFaild("未找到分配该岗位的用户");
            var userIds = userDepartmentDutys.Select(a => a.SysUserInforID);
            users = await _coreDBContext.SysUserInfor.Where(a => userIds.Contains(a.SysUserID)).ToListAsync();
            var returnModel = new
            {
                department,
                users
            };
            return this.JsonSuccess(returnModel);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet("PageInit")]
        public ActionResult PageInit([FromServices] ZY_DictService dictService, [FromServices] IDataDicHelp dataDicHelp)
        {
            var groupingData = dictService.QueryALLGroup();
            var dataDicList = dataDicHelp.GeDataDicValueByCategory(nameof(TicketTypeEnum));
            var returnModel = new
            {
                TypeB = groupingData.SingleOrDefault(a => a.Key == DicType.TypeB).Select(item => CreateKeyValue(item)),
                TypeC = groupingData.SingleOrDefault(a => a.Key == DicType.TypeC).Select(item => CreateKeyValue(item)),
                TypeD = groupingData.SingleOrDefault(a => a.Key == DicType.TypeD).Select(item => CreateKeyValue(item)),
                TypeE = groupingData.SingleOrDefault(a => a.Key == DicType.TypeE).Select(item => CreateKeyValue(item)),
                TypeF = groupingData.SingleOrDefault(a => a.Key == DicType.TypeF).Select(item => CreateKeyValue(item)),
                TicketTypes = dataDicList
            };
            return this.JsonSuccess(returnModel);
        }

        /// <summary>
        /// 创建许可证编号
        /// </summary>
        /// <returns></returns>
        [HttpGet("jobLicenseCode")]
        public ActionResult JobLicenseCode([FromServices] ZYSservice zYSservice)
        {
            var jobLicenseCode = zYSservice.CreateTicketNumber(TicketTypeEnum.Workermit, userId: UserIdentity.Id);
            return this.JsonSuccess(jobLicenseCode);
        }

        private CheckBoxModel CreateKeyValue(ZY_Dict dict)
        {
            return new CheckBoxModel { Lable = dict.DictCode, Text = dict.DictName, Value = "0" };
        }

        /// <summary>
        /// 列表页获取属地主管
        /// </summary>
        [HttpGet("TerritorialDirector/{departmentId}")]
        public async Task<ActionResult> TerritorialDirectorAsync(Guid departmentId)
        {
            var duty = await _coreDBContext.SysDuty.SingleOrDefaultAsync(a => a.SysDepartmentID == departmentId);
            var userIds = _coreDBContext.SysUserDepartmentDuty.Where(ud => ud.SysDutyID == duty.Id).Select(a => a.SysUserInforID);
            var users = _coreDBContext.SysUserInfor.Where(u => userIds.Contains(u.SysUserID));
            var viewModel = await users.Select(a => new { a.Name, id = a.Id }).ToListAsync();
            return this.JsonSuccess(viewModel);
        }

    }
}